package org.zyx.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    //定义相应类型常量
    private static final List<String> CONTENT_TYPES = Arrays.asList(
            "image/jpeg", "image/jpeg", "image/gif", "image/png");

    //定义Logger对象
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    @Autowired
    FastFileStorageClient storageClient; //文件存储客户端

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    public String uploadImage(MultipartFile file) {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //1.校验文件类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)) {
            //打印日志,记录错误信息
            LOGGER.info("文件类型不合法:{}", originalFilename);
            return null;
        }
        //2.校验文件内容
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());//返回一个二进制图片
            if (bufferedImage == null) {
                LOGGER.info("文件内容不合法:{}", originalFilename);
                return null;
            }
            //3.保存到服务器
            //file.transferTo(new File("E:\\IDEA_workspace\\MyProject\\YiYouStore\\image\\" + originalFilename));

            //3.1 将图片上传到FastDFS
            // 2.1、获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 2.2、上传
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), extension, null);
            System.out.println("http://image.yiyou.com/"+storePath.getFullPath());
            // 2.3、返回完整路径
            return "http://image.yiyou.com/" + storePath.getFullPath();


        } catch (IOException e) {
            LOGGER.info("服务器内部错误:{}", originalFilename);
            e.printStackTrace();
        }
        //4.返回url,进行回显
            //方法一:使用nginx代理图片路径
            //1.修改config:添加server配置,修改映射:image.yiyou.com,设置 root 为文件存储路径
            //2.添加host:127.0.0.1 image.yiyou.com
            //3.reload nginx,通过http://image.yiyou.com/图片.jpg 访问图片

        //方法二:使用fastDFS回显图片路径

        return null;
    }
}
